package com.java.test.functional.designPatterm;

import java.util.ArrayList;
import java.util.List;


public class ObserverMain {

    public static void main(String[] args) {
        Feed f = new Feed();
        f.registerObserver(new Observer1());
        f.registerObserver(new Observer2());
        f.notifyObservers("观察者1   观察者2");


        Feed feedLambda = new Feed();
        System.out.println();

        feedLambda.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("观察者1")){
                System.out.println("Java8 通知观察者1如下信息... " + tweet);
            }
        });
        feedLambda.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("观察者2")){
                System.out.println("Java8 通知观察者2如下信息... " + tweet);
            }
        });

        feedLambda.notifyObservers("观察者1   观察者2");

    }


    interface Observer{
        void inform(String tweet);
    }

    interface Subject{
        void registerObserver(Observer o);
        void notifyObservers(String tweet);
    }

    static private class Observer1 implements Observer{
        @Override
        public void inform(String tweet) {
            if(tweet != null && tweet.contains("观察者1")){
                System.out.println("Java7 通知观察者1如下信息... " + tweet);
            }
        }
    }

    static private class Observer2 implements Observer{
        @Override
        public void inform(String tweet) {
            if(tweet != null && tweet.contains("观察者2")){
                System.out.println("Java7 通知观察者2如下信息... " + tweet);
            }
        }
    }


    static private class Feed implements Subject{
        private final List<Observer> observers = new ArrayList<>();
        public void registerObserver(Observer o) {
            this.observers.add(o);
        }
        public void notifyObservers(String tweet) {
            observers.forEach(o -> o.inform(tweet));
        }
    }

}
